<template>
    <div :style="{'height':_height}" ref="scTableMainRef" v-loading="loading">
        <div class="scTable-table" :style="{'height':_table_height}">
            <el-table v-bind="$attrs" :data="tableData" :row-key="rowKey" :key="toggleIndex" ref="scTableRef" :height="height=='auto'?null:'100%'" :size="config.size" :border="config.border" :stripe="config.stripe" :summary-method="remoteSummary?remoteSummaryMethod:summaryMethod" @sort-change="sortChange" @filter-change="filterChange">
                <slot></slot>
                <template v-for="(item, index) in userColumn" :key="index">
                    <el-table-column v-if="!item.hide" :column-key="item.prop" :label="item.label" :prop="item.prop" :width="item.width" :sortable="item.sortable" :fixed="item.fixed" :filters="item.filters" :filter-method="remoteFilter||!item.filters?null:filterHandler" :show-overflow-tooltip="item.showOverflowTooltip">
                        <template #default="scope">
                            <slot :name="item.prop" v-bind="scope">{{scope.row[item.prop]}}</slot>
                        </template>
                    </el-table-column>
                </template>
				<el-table-column min-width="1"></el-table-column>
				<template #empty>
					<el-empty :description="emptyText" :image-size="100"></el-empty>
				</template>
            </el-table>
        </div>
        <div class="scTable-page" v-if="!hidePagination || !hideDo">
            <slot name="operation"></slot>
            <div class="scTable-pagination">
				<el-pagination v-if="!hidePagination" background :small="true" :layout="paginationLayout" :total="total" :page-size="scPageSize" :page-sizes="pageSizes" v-model:currentPage="currentPage" @current-change="paginationChange" @update:page-size="pageSizeChange"></el-pagination>
			</div>
            <div class="scTable-do" v-if="!hideDo">
				<el-button v-if="!hideRefresh" @click="refresh" icon="el-icon-refresh" circle style="margin-left:15px"></el-button>
				<el-popover v-if="column" placement="top" :title="$t('scTable.columnSet')" :width="500" trigger="click" :hide-after="0" @show="customColumnShow=true" @after-leave="customColumnShow=false">
					<template #reference>
						<el-button icon="el-icon-set-up" circle style="margin-left:15px"></el-button>
					</template>
					<columnSetting v-if="customColumnShow" ref="columnSettingRef" @userChange="columnSettingChange" @save="columnSettingSave" @back="columnSettingBack" :column="userColumn"></columnSetting>
				</el-popover>
				<el-popover v-if="!hideSetting" placement="top" :title="$t('scTable.tableSet')" :width="400" trigger="click" :hide-after="0">
					<template #reference>
						<el-button icon="el-icon-setting" circle style="margin-left:15px"></el-button>
					</template>
					<el-form label-width="80px" label-position="left">
						<el-form-item :label="$t('scTable.tableSize')">
							<el-radio-group v-model="config.size" size="small" @change="configSizeChange">
								<el-radio-button label="large">{{ $t('scTable.large') }}</el-radio-button>
								<el-radio-button label="default">{{ $t('scTable.default') }}</el-radio-button>
								<el-radio-button label="small">{{ $t('scTable.small') }}</el-radio-button>
							</el-radio-group>
						</el-form-item>
						<el-form-item :label="$t('scTable.tableStyle')">
							<el-checkbox v-model="config.border" :label="$t('scTable.border')"></el-checkbox>
							<el-checkbox v-model="config.stripe" :label="$t('scTable.stripe')"></el-checkbox>
						</el-form-item>
					</el-form>
				</el-popover>
            </div>
        </div>
    </div>
</template>
<script setup>
import { ref, reactive, watch, computed, onMounted ,onActivated, onDeactivated } from 'vue'
import sysconfig from "@/config/table";
import columnSetting from './columnSetting.vue';
import { ElMessage } from 'element-plus';
import i18n from '@/locales';

// 接收父组件的传值
const props = defineProps({
    tableName: { type: String, default: "" },
    apiObj: { type: Object, default: () => {} },
    params: { type: Object, default: () => ({}) },
    data: { type: Object, default: () => {} },
    height: { type: [String,Number], default: "100%" },
    size: { type: String, default: "default" },
    border: { type: Boolean, default: false },
    stripe: { type: Boolean, default: false },
    pageSize: { type: Number, default: sysconfig.pageSize },
    pageSizes: { type: Array, default: sysconfig.pageSizes },
    rowKey: { type: String, default: "" },
    summaryMethod: { type: Function, default: null },
    column: { type: Object, default: () => {} },
    remoteSort: { type: Boolean, default: false },
    remoteFilter: { type: Boolean, default: false },
    remoteSummary: { type: Boolean, default: false },
    hidePagination: { type: Boolean, default: false },
    hideDo: { type: Boolean, default: false },
    hideRefresh: { type: Boolean, default: false },
    hideSetting: { type: Boolean, default: false },
    paginationLayout: { type: String, default: sysconfig.paginationLayout },
});
// 定义用于发射更新事件的方法
const emit = defineEmits(['dataChange']);
// 定义响应式数据
const scPageSize = ref(props.pageSize);
const isActivat = ref(true);
const emptyText = ref(i18n.global.t('scTable.noData'));
const toggleIndex = ref(0);
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const prop = ref(null);
const order = ref(null);
const loading = ref(false);
const tableHeight = ref('100%');
const tableParams = ref(props.params);
const userColumn = ref([]);
const customColumnShow = ref(false);
const summary = ref({});
const config = reactive({
    size: props.size,
    border: props.border,
    stripe: props.stripe,
});
const scTableMainRef = ref(null);
const scTableRef = ref(null);
const columnSettingRef = ref(null);
const _height = computed(() => Number(props.height) ? Number(props.height)+'px' : props.height);
const _table_height = computed(() => props.hidePagination && props.hideDo ? "100%" : "calc(100% - 50px)");
// 监听 props.data 的变化
watch(() => props.data, () => {
    tableData.value = props.data;
    total.value = tableData.value.length;
}, { deep: true });
watch(() => props.apiObj, () => {
    tableParams.value = props.params;
    refresh();
}, { deep: true });
watch(() => props.column, () => {
    userColumn.value = props.column;
}, { deep: true });
// 组件挂载时加载数据
onMounted(() => {
    // 判断是否开启自定义列
    if (props.column) {
        getCustomColumn();
    } else {
        userColumn.value = props.column;
    }
    // 判断是否静态数据
    if (props.apiObj) {
        getData();
    } else if (props.data) {
        tableData.value = props.data;
        total.value = tableData.value.length;
    }
});
onActivated(() => {
    if (!isActivat.value) {
        scTableRef.value.doLayout();
    }
});
onDeactivated(() => {
    isActivat.value = false;
});
// 自定义获取列的方法
const getCustomColumn = async() => {
    const userColumn = await sysconfig.columnSettingGet(props.tableName, props.column);
    userColumn.value = userColumn;
};
// 自定义获取数据的方法
const getData = async () => {
    loading.value = true;
    const reqData = {
        [sysconfig.request.page]: currentPage.value,
        [sysconfig.request.pageSize]: scPageSize.value,
        [sysconfig.request.prop]: prop.value,
        [sysconfig.request.order]: order.value,
    };
    if (props.hidePagination) {
        delete reqData[sysconfig.request.page];
        delete reqData[sysconfig.request.pageSize];
    };
    Object.assign(reqData, tableParams.value);
    try {
        var res = await props.apiObj.get(reqData);
    } catch (error) {
        emptyText.value = error.statusText;
        return false;
    } finally {
        loading.value = false;
    };
    try {
        var response = sysconfig.parseData(res);
    } catch (error) {
        emptyText.value = i18n.global.t('scTable.dataError');
        return false;
    } finally {
        loading.value = false;
    };
    if (response.code != sysconfig.successCode) {
        emptyText.value = response.msg;
    } else {
        emptyText.value = i18n.global.t('scTable.noData');
        if (props.hidePagination) {
            tableData.value = response.data || [];
        } else {
            tableData.value = response.rows || [];
        };
        total.value = response.total || 0;
        summary.value = response.summary || {};
    };
    if (scTableRef.value) scTableRef.value.setScrollTop(0);
    emit('dataChange', res, tableData.value);
};
// 自定义分页点击的方法
const paginationChange = () => {
    getData();
};
// 自定义条数变化的方法
const pageSizeChange = (size) => {
    scPageSize.value = size;
    getData();
}
// 自定义刷新数据的方法
const refresh = () => {
    scTableRef.value.clearSelection();
    getData();
};
// 自定义更新数据的方法 合并上一次params
const upData = (params, page=1) => {
    currentPage.value = page;
    scTableRef.value.clearSelection();
    Object.assign(tableParams.value, params || {});
    getData();
};
// 自定义重载数据的方法 替换params
const reload = (params, page=1) => {
    currentPage.value = page;
    tableParams.value = params || {};
    scTableRef.value.clearSelection();
    scTableRef.value.clearSort();
    scTableRef.value.clearFilter();
    getData();
};
// 自定义变化事件的方法
const columnSettingChange = (userColumn) => {
    userColumn.value = userColumn;
    toggleIndex.value += 1;
};
// 自定义列保存的方法
const columnSettingSave = async (userColumn) => {
    columnSettingRef.value.isSave = true;
    try {
        await sysconfig.columnSettingSave(props.tableName, userColumn);
        ElMessage.success(i18n.global.t('common.saveSuccess'));
    } catch (error) {
        ElMessage.error(i18n.global.t('common.saveError'));
    } finally {
        columnSettingRef.value.isSave = false;
    }
};
// 自定义列重置的方法
const columnSettingBack = async () => {
    columnSettingRef.value.isSave = true;
    try {
        const column = await sysconfig.columnSettingReset(props.tableName, props.column);
        userColumn.value = column;
        columnSettingRef.value.usercolumn = JSON.parse(JSON.stringify(userColumn.value||[]));
        ElMessage.success(i18n.global.t('common.resetSuccess'));
    } catch (error) {
        ElMessage.error(i18n.global.t('common.resetError'));
    } finally {
        columnSettingRef.value.isSave = false;
    }
};
// 自定义排序事件的方法
const sortChange = (obj) => {
    if(!props.remoteSort) {
        return false;
    };
    if(obj.column && obj.prop) {
        prop.value = obj.prop;
        order.value = obj.order;
    } else {
        prop.value = null;
        order.value = null;
    }
    getData();
};
// 自定义本地过滤的方法
const filterHandler = (value, row, column) => {
    const property = column.property;
    return row[property] === value;
};
// 自定义过滤事件的方法
const filterChange = (filters) => {
    if(!props.remoteFilter) {
        return false;
    }
    Object.keys(filters).forEach(key => {
        filters[key] = filters[key].join(',');
    })
    upData(filters);
};
// 自定义远程合计行处理的方法
const remoteSummaryMethod = (param) => {
    const {columns} = param;
    const sums = [];
    columns.forEach((column, index) => {
        if(index === 0) {
            sums[index] = i18n.global.t('scTable.total');
            return;
        }
        const values =  summary.value[column.property];
        if (values) {
            sums[index] = values;
        } else {
            sums[index] = '';
        }
    });
    return sums;
};
const configSizeChange = () => {
    scTableRef.value.doLayout();
};
// 自定义删除行的方法
const unshiftRow = (row) => {
    tableData.value.unshift(row);
};
// 自定义插入行的方法
const pushRow = () => {
    tableData.value.push(row);
};
// 自定义根据key覆盖数据的方法
const updateKey = (row, rowKey = props.rowKey) => {
    tableData.value.filter(item => item[rowKey]===row[rowKey] ).forEach(item => {
        Object.assign(item, row);
    });
};
// 自定义根据index覆盖数据的方法
const updateIndex = (row, index) => {
    Object.assign(tableData.value[index], row);
};
// 自定义根据index删除的方法
const removeIndex = (index) => {
    tableData.value.splice(index, 1);
};
// 自定义根据index批量删除的方法
const removeIndexes = (indexes=[]) => {
    indexes.forEach(index => {
        tableData.value.splice(index, 1);
    })
};
// 自定义根据key删除的方法
const removeKey = (key, rowKey = props.rowKey) => {
    tableData.value.splice(tableData.value.findIndex(item => item[rowKey]===key), 1);
};
// 自定义根据keys批量删除的方法
const removeKeys = (keys=[], rowKey = props.rowKey) => {
    keys.forEach(key => {
        tableData.value.splice(tableData.value.findIndex(item => item[rowKey]===key), 1);
    })
};
// 自定义原生方法转发的方法
const clearSelection = () => {
    scTableRef.value.clearSelection();
};
const toggleRowSelection = (row, selected) => {
    scTableRef.value.toggleRowSelection(row, selected);
};
const toggleAllSelection = () => {
    scTableRef.value.toggleAllSelection();
};
const toggleRowExpansion = (row, expanded) => {
    scTableRef.value.toggleRowExpansion(row, expanded);
};
const setCurrentRow = (row) => {
    scTableRef.value.setCurrentRow(row);
};
const clearSort = () => {
    scTableRef.value.clearSort();
};
const clearFilter = (columnKey) => {
    scTableRef.value.clearFilter(columnKey);
};
const doLayout = () => {
    scTableRef.value.doLayout();
};
const sort = (prop, order) => {
    scTableRef.value.sort(prop, order);
};
defineExpose({refresh, upData, reload, tableData, toggleAllSelection, clearSelection});
</script>
<style scoped>
	.scTable-table {height: calc(100% - 50px);}
	.scTable-page {height:50px;display: flex;align-items: center;justify-content: space-between;padding:0 15px;}
	.scTable-do {white-space: nowrap;}
	.scTable:deep(.el-table__footer) .cell {font-weight: bold;}
	.scTable:deep(.el-table__body-wrapper) .el-scrollbar__bar.is-horizontal {height: 12px;border-radius: 12px;}
	.scTable:deep(.el-table__body-wrapper) .el-scrollbar__bar.is-vertical {width: 12px;border-radius: 12px;}
</style>